<template>
  <div class="detail">
    <el-container>
      <el-main>
        <!-- 加载状态 -->
        <div v-if="loading" class="loading">
          <el-progress :percentage="50" />
          <p>加载中...</p>
        </div>

        <!-- 视频详情 -->
        <div v-else-if="videoData" class="video-detail">
          <div class="detail-header">
            <img :src="videoData.thumbnail" :alt="videoData.title" class="detail-thumbnail" />
            <div class="detail-info">
              <h1>{{ videoData.title }}</h1>
              <div class="meta-info">
                <span>{{ formatViews(videoData.views) }} 次播放</span>
                <span>{{ formatDate(videoData.created_at) }}</span>
                <span>{{ videoData.duration }}</span>
                <span>{{ videoData.category?.name || '未分类' }}</span>
              </div>
              <p class="description">{{ videoData.description }}</p>
              <div class="actions">
                <el-button type="primary" @click="playVideo">
                  <el-icon><CaretRight /></el-icon>立即播放
                </el-button>
                <el-button @click="toggleLike">
                  <el-icon><Star /></el-icon>{{ videoData.likes }} 点赞
                </el-button>
                <el-button @click="shareVideo">
                  <el-icon><Share /></el-icon>分享
                </el-button>
              </div>
            </div>
          </div>

          <el-divider />

          <div class="tabs-section">
            <el-tabs v-model="activeTab">
              <el-tab-pane label="简介" name="intro">
                <div class="intro-content">
                  <p><strong>上传者:</strong> {{ videoData.user?.name || '未知用户' }}</p>
                  <p><strong>分类:</strong> {{ videoData.category?.name || '未分类' }}</p>
                  <p><strong>上传时间:</strong> {{ formatDate(videoData.created_at) }}</p>
                  <p><strong>播放次数:</strong> {{ formatViews(videoData.views) }}</p>
                  <p><strong>点赞数:</strong> {{ videoData.likes }}</p>
                  <p><strong>视频时长:</strong> {{ videoData.duration }}</p>
                  <p><strong>简介:</strong></p>
                  <p>{{ videoData.description }}</p>
                </div>
              </el-tab-pane>
              <el-tab-pane label="评论" name="comments">
                <div class="comments">
                  <div class="comment-form">
                    <el-input
                      v-model="newComment"
                      type="textarea"
                      :rows="3"
                      placeholder="写下你的评论..."
                    />
                    <el-button type="primary" style="margin-top: 10px" @click="submitComment">发表评论</el-button>
                  </div>
                  
                  <div class="comment-list">
                    <div v-if="comments.length === 0" class="no-comments">
                      <p>暂无评论，快来抢沙发吧！</p>
                    </div>
                    <div v-for="comment in comments" :key="comment.id" class="comment-item">
                      <img :src="comment.user?.avatar || '/images/avatars/default.jpg'" alt="avatar" class="comment-avatar" />
                      <div class="comment-content">
                        <div class="comment-header">
                          <span class="username">{{ comment.user?.name || '匿名用户' }}</span>
                          <span class="time">{{ formatDate(comment.created_at) }}</span>
                        </div>
                        <p>{{ comment.content }}</p>
                        <div class="comment-actions">
                          <el-button size="small" text @click="likeComment(comment.id)">
                            <el-icon><Star /></el-icon> {{ comment.likes || 0 }}
                          </el-button>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>

        <!-- 错误状态 -->
        <div v-else class="error">
          <h2>视频不存在</h2>
          <p>抱歉，您访问的视频不存在或已被删除。</p>
          <el-button type="primary" @click="goHome">返回首页</el-button>
        </div>

        <!-- 推荐视频 -->
        <div v-if="recommendations.length > 0" class="recommendations">
          <h2>推荐视频</h2>
          <div class="recommend-grid">
            <div
              v-for="video in recommendations"
              :key="video.id"
              class="rec-video"
              @click="goToDetail(video.id)"
            >
              <img :src="video.thumbnail" :alt="video.title" />
              <div class="rec-info">
                <h4>{{ video.title }}</h4>
                <p>{{ formatViews(video.views) }} 次播放</p>
                <span>{{ video.duration }}</span>
              </div>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  ElContainer,
  ElMain,
  ElButton,
  ElIcon,
  ElDivider,
  ElTabs,
  ElTabPane,
  ElInput,
  ElProgress
} from 'element-plus'
import { CaretRight, Star, Share } from '@element-plus/icons-vue'
import api from '@/utils/axios'

const router = useRouter()
const route = useRoute()
const activeTab = ref('intro')
const newComment = ref('')
const loading = ref(true)
const videoData = ref(null)
const comments = ref([])
const recommendations = ref([])

// 格式化播放量
const formatViews = (views) => {
  if (views >= 10000) {
    return (views / 10000).toFixed(1) + '万'
  }
  return views.toString()
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 加载视频详情
const loadVideoDetail = async (id) => {
  try {
    loading.value = true
    const response = await api.get(`/videos/${id}`)
    if (response.success) {
      videoData.value = response.data
      // 增加播放次数
      await incrementViews(id)
    } else {
      ElMessage.error('视频不存在')
      videoData.value = null
    }
  } catch (error) {
    console.error('加载视频详情失败:', error)
    ElMessage.error('加载视频详情失败')
    videoData.value = null
  } finally {
    loading.value = false
  }
}

// 增加播放次数
const incrementViews = async (id) => {
  try {
    await api.post(`/videos/${id}/view`)
  } catch (error) {
    console.error('增加播放次数失败:', error)
  }
}

// 加载评论
const loadComments = async (id) => {
  try {
    const response = await api.get(`/videos/${id}/comments`)
    if (response.success) {
      comments.value = response.data
    }
  } catch (error) {
    console.error('加载评论失败:', error)
  }
}

// 加载推荐视频
const loadRecommendations = async () => {
  try {
    const response = await api.get('/videos/recommended')
    if (response.success) {
      // 过滤掉当前视频
      recommendations.value = response.data.filter(video => video.id !== videoData.value?.id).slice(0, 6)
    }
  } catch (error) {
    console.error('加载推荐视频失败:', error)
  }
}

// 播放视频
const playVideo = () => {
  if (videoData.value) {
    router.push(`/player/${videoData.value.id}`)
  }
}

// 点赞视频
const toggleLike = async () => {
  if (!videoData.value) return
  
  try {
    const response = await api.post(`/videos/${videoData.value.id}/like`)
    if (response.success) {
      videoData.value.likes = response.likes
      ElMessage.success('点赞成功')
    }
  } catch (error) {
    console.error('点赞失败:', error)
    ElMessage.error('点赞失败')
  }
}

// 分享视频
const shareVideo = () => {
  if (navigator.share) {
    navigator.share({
      title: videoData.value.title,
      text: videoData.value.description,
      url: window.location.href
    })
  } else {
    // 复制链接到剪贴板
    navigator.clipboard.writeText(window.location.href).then(() => {
      ElMessage.success('链接已复制到剪贴板')
    })
  }
}

// 发表评论
const submitComment = async () => {
  if (!newComment.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
  
  if (!videoData.value) return
  
  try {
    const response = await api.post(`/videos/${videoData.value.id}/comments`, {
      content: newComment.value
    })
    if (response.success) {
      ElMessage.success('评论发表成功')
      newComment.value = ''
      // 重新加载评论
      loadComments(videoData.value.id)
    }
  } catch (error) {
    console.error('发表评论失败:', error)
    ElMessage.error('发表评论失败')
  }
}

// 点赞评论
const likeComment = async (commentId) => {
  try {
    const response = await api.post(`/comments/${commentId}/like`)
    if (response.success) {
      // 更新评论的点赞数
      const comment = comments.value.find(c => c.id === commentId)
      if (comment) {
        comment.likes = response.likes
      }
    }
  } catch (error) {
    console.error('点赞评论失败:', error)
  }
}

// 跳转到详情页
const goToDetail = (id) => {
  router.push(`/detail/${id}`)
}

// 返回首页
const goHome = () => {
  router.push('/home')
}

onMounted(async () => {
  const id = route.params.id
  if (id) {
    await loadVideoDetail(id)
    if (videoData.value) {
      await loadComments(id)
      await loadRecommendations()
    }
  }
})
</script>

<style scoped>
.detail {
  width: 100vw;
  max-width: none;
  min-height: 100vh;
  background: #0a0a0a;
  color: #fff;
  padding: 40px 20px;
  margin: 0;
}

.loading {
  text-align: center;
  padding: 60px 20px;
}

.loading p {
  margin-top: 20px;
  color: #999;
}

.error {
  text-align: center;
  padding: 60px 20px;
}

.error h2 {
  margin-bottom: 20px;
  color: #ff6b6b;
}

.error p {
  margin-bottom: 30px;
  color: #999;
}

.detail-header {
  display: flex;
  gap: 40px;
  margin-bottom: 40px;
  width: 100%;
  padding: 0 20px;
}

.detail-thumbnail {
  width: 600px;
  height: 338px;
  object-fit: cover;
  border-radius: 12px;
  flex-shrink: 0;
}

.detail-info {
  flex: 1;
}

.detail-info h1 {
  font-size: 32px;
  margin-bottom: 20px;
}

.meta-info {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  color: #999;
  font-size: 14px;
}

.description {
  margin-bottom: 20px;
  font-size: 16px;
  line-height: 1.6;
}

.actions {
  display: flex;
  gap: 10px;
}

.intro-content p {
  margin-bottom: 10px;
  line-height: 1.8;
}

.comment-form {
  margin-bottom: 30px;
  padding: 20px;
  background: #1a1a1a;
  border-radius: 8px;
}

.comment-list {
  margin-top: 30px;
}

.no-comments {
  text-align: center;
  padding: 40px 20px;
  color: #999;
}

.comment-item {
  display: flex;
  gap: 15px;
  padding: 15px 0;
  border-bottom: 1px solid #2a2a2a;
}

.comment-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  gap: 10px;
  margin-bottom: 8px;
}

.username {
  font-weight: bold;
}

.time {
  color: #666;
  font-size: 12px;
}

.comment-actions {
  margin-top: 8px;
}

.tabs-section {
  width: 100%;
  padding: 0 20px;
  margin-bottom: 40px;
}

.recommendations {
  margin-top: 60px;
  padding: 0 20px;
  width: 100%;
}

.recommend-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.rec-video {
  cursor: pointer;
  transition: transform 0.3s;
}

.rec-video:hover {
  transform: translateY(-5px);
}

.rec-video img {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 10px;
}

.rec-info h4 {
  font-size: 14px;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.rec-info p {
  font-size: 12px;
  color: #999;
  margin-bottom: 3px;
}

.rec-info span {
  font-size: 12px;
  color: #666;
}

@media (max-width: 768px) {
  .detail-header {
    flex-direction: column;
  }
  
  .detail-thumbnail {
    width: 100%;
    height: 200px;
  }
  
  .actions {
    flex-wrap: wrap;
  }
  
  .recommend-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
}
</style>

